package com.api.shopapi.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.ElderlyDTO;
import com.api.shopapi.entity.dto.RechargeDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 充值
 * */

@RestController
@RequestMapping("Recharge")
public class RechargeController extends BaseController {

    @Autowired
    @Qualifier("RechargeServiceImplOne")
    private RechargeService rechargeService;


    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    @Autowired
    @Qualifier("RechargeGroupServiceImplOne")
    private RechargeGroupService rechargeGroupService;


    //政府补贴充值
    @RequestMapping(value = "GovernmentPay", method = RequestMethod.POST)
    @Transactional
    public MyResult GovernmentPay(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Recharge/GovernmentPay");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }



            Staff staff = staffService.getByStaffCode(staffCode);


            String elderlyCode = jsonObject.getString("elderlyCode");
            ElderlyDTO elderlyDTO = elderlyService.getByElderlyCode(elderlyCode);
            double balance = elderlyDTO.getBalance();
            String rechargeCode = UUID.randomUUID().toString();
            double addBalance = jsonObject.getDouble("addBalance");
            double payMoney = jsonObject.getDouble("payMoney");

            balance = balance + addBalance;
            elderlyDTO.setBalance(balance);

            String governmentCode = staff.getGovernmentCode();

            RechargeDTO rechargeDTO = new RechargeDTO();
            rechargeDTO.setRechargeCode(rechargeCode);
            rechargeDTO.setElderlyCode(elderlyCode);
            rechargeDTO.setPayMoney(payMoney);
            rechargeDTO.setAddBalance(addBalance);
            rechargeDTO.setCreateTime(new Date());
            rechargeDTO.setStaffCode(staffCode);
            rechargeDTO.setGovernmentCode(governmentCode);
            rechargeDTO.setType(1);

            rechargeService.insert(rechargeDTO);
            elderlyService.update(elderlyDTO);

            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            insertError("/Recharge/GovernmentPay",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //高龄补贴充值
    @RequestMapping(value = "OldestPay", method = RequestMethod.POST)
    public MyResult OldestPay(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Recharge/OldestPay");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            Staff staff = staffService.getByStaffCode(staffCode);
            String elderlyCode = jsonObject.getString("elderlyCode");
            ElderlyDTO elderlyDTO = elderlyService.getByElderlyCode(elderlyCode);
            double balance = elderlyDTO.getBalance();
            String rechargeCode = UUID.randomUUID().toString();
            double addBalance = jsonObject.getDouble("addBalance");

            balance = balance + addBalance;
            elderlyDTO.setBalance(balance);

            String governmentCode = staff.getGovernmentCode();

            RechargeDTO rechargeDTO = new RechargeDTO();
            rechargeDTO.setRechargeCode(rechargeCode);
            rechargeDTO.setElderlyCode(elderlyCode);
            rechargeDTO.setPayMoney(0);
            rechargeDTO.setAddBalance(addBalance);
            rechargeDTO.setCreateTime(new Date());
            rechargeDTO.setStaffCode(staffCode);
            rechargeDTO.setGovernmentCode(governmentCode);
            rechargeDTO.setType(2);
            Date lastRechargeTime=new Date();
            rechargeService.insert(rechargeDTO);
            elderlyService.update(elderlyDTO);
//            elderlyService.updateBalance(balance, elderlyCode,lastRechargeTime);

            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            insertError("/Recharge/OldestPay",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //列表
    @RequestMapping(value = "Page", method = RequestMethod.POST)
    public MyResult Page(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String startTime = jsonObject.getString("startTime");
            String endTime = jsonObject.getString("endTime");
            SimpleDateFormat am = new SimpleDateFormat("yyyy-MM-dd");
            Date date = am.parse(endTime);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
            date=calendar.getTime();
            endTime = am.format(date);
            System.out.println(startTime);
            System.out.println(endTime);

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Recharge/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff =staffService.getByStaffCode(staffCode);
            String governmentCode=staff.getGovernmentCode();


            PageInfo<RechargeDTO> rechargeDTOPageInfo = rechargeService.getPageList1(pageIndex, pageSize, name,phone,governmentCode,startTime,endTime);
            List<RechargeDTO> rechargeDTOList = rechargeDTOPageInfo.getList();

            for (RechargeDTO rechargeDTO : rechargeDTOList) {

                ElderlyDTO elderlyDTO = elderlyService.getByElderlyCode(rechargeDTO.getElderlyCode());
                if(elderlyDTO==null){
                    continue;
                }


                User user =userService.getByUserCode(elderlyDTO.getUserCode());
                if(user==null){
                    elderlyDTO.setUserPhone(null);
                }else {
                    elderlyDTO.setUserPhone(user.getPhone());
                }
                rechargeDTO.setElderlyDTO(elderlyDTO);
            }
            return success(rechargeDTOPageInfo);
        } catch (Exception e) {
//            e.printStackTrace();
            insertError("/Recharge/Page",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //政府补贴批量充值
    @RequestMapping(value = "BatchPay", method = RequestMethod.POST)
    @Transactional
    public MyResult BatchPay(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Recharge/BatchPay");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }



            Staff staff =staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();
            
            double addBalance=jsonObject.getDouble("addBalance");
            double payMoney = jsonObject.getDouble("payMoney");

            JSONArray elderlyCodeList = jsonObject.getJSONArray("elderlyCodeList");
            int j =elderlyCodeList.size();

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String date =formatter.format(new Date());

            RechargeGroup rechargeGroup=new RechargeGroup();
            rechargeGroup.setRechargeGroupCode(UUID.randomUUID().toString());
            rechargeGroup.setName(date);
            rechargeGroup.setCreateTime(new Date());
            rechargeGroup.setStaffCode(staffCode);
            rechargeGroup.setGovernmentCode(governmentCode);
            rechargeGroup.setTotalMoney(addBalance*j);
            rechargeGroup.setTotalElderly(j);
            rechargeGroup.setRechargeType(2);

            for (int i=0;i<j;i++){
                String elderlyCode=elderlyCodeList.getString(i);
                ElderlyDTO elderlydto =elderlyService.getByElderlyCode(elderlyCode);
                double balance=elderlydto.getBalance();
                balance=balance+addBalance;

                elderlydto.setBalance(balance);
                String rechargeCode = UUID.randomUUID().toString();

                RechargeDTO rechargeDTO = new RechargeDTO();
                rechargeDTO.setRechargeCode(rechargeCode);
                rechargeDTO.setElderlyCode(elderlyCode);
                rechargeDTO.setPayMoney(payMoney);
                rechargeDTO.setAddBalance(addBalance);
                rechargeDTO.setCreateTime(new Date());
                rechargeDTO.setStaffCode(staffCode);
                rechargeDTO.setGovernmentCode(governmentCode);
                rechargeDTO.setType(1);
                rechargeDTO.setRechargeGroupCode(rechargeGroup.getRechargeGroupCode());
                rechargeService.insert(rechargeDTO);
                elderlyService.update(elderlydto);

            }
            rechargeGroupService.insert(rechargeGroup);


            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            insertError("/Recharge/BatchPay",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }



    //筛选批量充值
    @RequestMapping(value = "FiltrateBatchRecharge",method = RequestMethod.POST)
    @Transactional
    public  MyResult FiltrateBatchRecharge(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Recharge/FiltrateBatchRecharge");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }




            Staff staff=staffService.getByStaffCode(staffCode);
            String governmentCode=staff.getGovernmentCode();

            String zoneCode= jsonObject.getString("zoneCode");
            String phone = jsonObject.getString("phone");
            String name = jsonObject.getString("name");
            int censusRegister= jsonObject.getInteger("censusRegister");
            int elderlyClass= jsonObject.getInteger("elderlyClass");

            double addBalance=jsonObject.getDouble("addBalance");
            double payMoney = jsonObject.getDouble("payMoney");

            List<ElderlyDTO> elderlyDTOList=elderlyService.getFiltrateBatchRechargeElderly(zoneCode,phone,governmentCode,name,censusRegister,elderlyClass);
            int j =elderlyDTOList.size();


            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String date =formatter.format(new Date());

            RechargeGroup rechargeGroup=new RechargeGroup();
            rechargeGroup.setRechargeGroupCode(UUID.randomUUID().toString());
            rechargeGroup.setName(date);
            rechargeGroup.setCreateTime(new Date());
            rechargeGroup.setStaffCode(staffCode);
            rechargeGroup.setGovernmentCode(governmentCode);
            rechargeGroup.setTotalMoney(addBalance*j);
            rechargeGroup.setTotalElderly(j);
            rechargeGroup.setRechargeType(2);

            for (int i=0;i<j;i++){
                ElderlyDTO elderlyDTO =elderlyDTOList.get(i);

                double balance=elderlyDTO.getBalance();
                balance=balance+addBalance;

                elderlyDTO.setBalance(balance);
                String rechargeCode = UUID.randomUUID().toString();

                RechargeDTO rechargeDTO = new RechargeDTO();
                rechargeDTO.setRechargeCode(rechargeCode);
                rechargeDTO.setElderlyCode(elderlyDTO.getElderlyCode());
                rechargeDTO.setPayMoney(payMoney);
                rechargeDTO.setAddBalance(addBalance);
                rechargeDTO.setCreateTime(new Date());
                rechargeDTO.setStaffCode(staffCode);
                rechargeDTO.setGovernmentCode(governmentCode);
                rechargeDTO.setType(1);
                rechargeDTO.setRechargeGroupCode(rechargeGroup.getRechargeGroupCode());
                rechargeService.insert(rechargeDTO);
                elderlyService.update(elderlyDTO);

            }
            rechargeGroupService.insert(rechargeGroup);

            JSONObject jsonObject1=new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
//            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            insertError("/Recharge/FiltrateBatchRecharge",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }



    @Value("${my.templates.test22}")
    protected String templatesPath22;


    //批量充值模板下载
    @RequestMapping(value = "BatchRechargeImport", method = RequestMethod.GET)
    public MyResult BatchRechargeImport(@RequestParam("timeStr") String timeStr,
                                        @RequestParam("sign") String sign,
                                        @RequestParam("staffCode") String staffCode,
                                        HttpServletResponse response) {
        try {


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Recharge/BatchRechargeImport");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            ClassPathResource classPathResource = new ClassPathResource(templatesPath22);
            InputStream inputStream = classPathResource.getInputStream();
            File somethingFile = File.createTempFile("批量充值", ".xlsx");
            FileUtils.copyInputStreamToFile(inputStream, somethingFile);
            String templateFileName = somethingFile.getAbsolutePath();
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("批量充值", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).sheet().doWrite(null);
            JSONObject jsonObject = new JSONObject();
            return success(jsonObject);
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }



    //列表
    @RequestMapping(value = "PageToGovPlatform", method = RequestMethod.POST)
    public MyResult PageToGovPlatform(@RequestBody JSONObject jsonObject) {
        try {

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String governmentCode = jsonObject.getString("governmentCode");


            PageInfo<RechargeDTO> rechargeDTOPageInfo = rechargeService.getPageList(pageIndex, pageSize, name,phone,governmentCode);
            List<RechargeDTO> rechargeDTOList = rechargeDTOPageInfo.getList();

            for (RechargeDTO rechargeDTO : rechargeDTOList) {

                ElderlyDTO elderlyDTO = elderlyService.getByElderlyCode(rechargeDTO.getElderlyCode());
                if(elderlyDTO==null){
                    continue;
                }


                User user =userService.getByUserCode(elderlyDTO.getUserCode());
                if(user==null){
                    elderlyDTO.setUserPhone(null);
                }else {
                    elderlyDTO.setUserPhone(user.getPhone());
                }
                rechargeDTO.setElderlyDTO(elderlyDTO);
            }
            return success(rechargeDTOPageInfo);
        } catch (Exception e) {
//            e.printStackTrace();
            insertError("/Recharge/PageToGovPlatform",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }



}
